package com.maizhe.util;

import com.ultrapower.casp.client.LoginUtil;
import com.ultrapower.casp.client.config.CaspClientConfig;
import com.ultrapower.casp.common.code.ResultCode;
import com.ultrapower.casp.common.datatran.data.ticket.TransferTicket;
import com.ultrapower.casp.common.datatran.data.user.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * created by wangh on 2021/1/11.
 */
@Component
public class SsoUtil extends HttpServlet {

    private static final Logger logger = LoggerFactory.getLogger(SsoUtil.class);

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp) {

        //系统启动时要初始化配置
        //可以随系统启动时，一次性初始化，如 com.init.Init
        //也可以随用户单点时，每次初始化
        String classUrl = CaspClientConfig.class.getResource("/").getFile();
        LoginUtil.getInstance().initCustom(classUrl + "casp_client_config.properties",classUrl + "casp_client_config.xml");

        if (LoginUtil.getInstance().isEnable()) {
            if (LoginUtil.getInstance().checkTicket(req)) { //ticket不为null
                String strTic = LoginUtil.getInstance().getTicket(req);
                System.out.println("登录票据：" + strTic);
                TransferTicket ticket = LoginUtil.getInstance().analysTicket(strTic);

                System.out.println("解析后票据为：" + ticket.customerObjToStr());

                req.setAttribute("rootTicket", ticket.getRootTicket());
//                req.getSession().setAttribute("rootTicket", ticket.getRootTicket());
                System.out.println("根票据：" + ticket.getRootTicket());

                // 主账号
//				UserInfo user = LoginUtil.getInstance().qryIAMUserIDByRTicket(
//						ticket.getRootTicket(), ticket.getTargetAppCode());
//				System.out.println("主账号：" + user.getAccountID());

                //应用方自行保存根票据，存入登录会话中，多个场景会用到，如金库
                if (ticket.getRetCode() != null && ResultCode.RESULT_OK.equals(ticket.getRetCode())) {
                    // 从账号
                    UserInfo userInfo = LoginUtil.getInstance().qryUserByTicket(ticket);

                    if (userInfo == null || !ResultCode.RESULT_OK.equals(userInfo.getRetCode())) {
                        // 跳转到错误页面，显示错误码；
                        System.out.println("-----------单点登录失败----------------");
                        logger.error("-------单点登录失败,code为：--------" + userInfo.getRetCode());

                        req.setAttribute("retCode", userInfo.getRetCode());//保存登录失败code
                    } else {
                        //应用系统在此处编写单点登录成功后的逻辑
                        //请将userInfo.getAccountID()　和  ticket.getRootTicket() 保存用户会话当中
                        System.out.println("-------单点登录成功--------");
                        System.out.println("从账号是：" + userInfo.getAccountID());
                        logger.error("-------单点登录成功--------");

                        req.setAttribute("userInfo", userInfo);//保存用户信息
                    }
                } else {
                    // 跳转到错误页面，显示错误码；

                    req.setAttribute("retCode", ticket.getRetCode());//保存登录失败code
                }
                return;
            }

            if (LoginUtil.getInstance().hasAliveServer()) {
                LoginUtil.getInstance().redirectToServer(req, resp);
            } else {
                // 使用应用资源本地认证；
                // 跳转到应急
            }
        } else {
            // 使用应用资源本地认证；
            // 跳转到应急
        }
    }

    @Override
    public void init() throws ServletException {

    }

    /**
     * 登录超时或失败跳转4A登录页
     */
    public void redirectLoginPage(HttpSession session) {
        String rootTicket = (String) session.getAttribute("rootTicket");

//        session.removeAttribute("rootTicket");
        session.invalidate();

        LoginUtil.getInstance().logout(rootTicket);
    }
}
